# coding=utf-8
# Create your views here.
from django.shortcuts import render, redirect, HttpResponse
from django.views.generic import View
from django import db
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login, logout
from django.core.paginator import Paginator, EmptyPage, InvalidPage, PageNotAnInteger  # 分页
from models import Staff, Project, Job, Task
import time
import datetime
import json
# from guardian.core import ObjectPermissionChecker
# 验证登录，及用户的权限
# from django.contrib.auth.decorators import login_required, permission_required


class RegisterView(View):
    """注册"""

    def get(self, request):
        return render(request, "register.html")

    def post(self, request):
        # 1 获取数据
        user_name = request.POST.get("user_name")
        pwd = request.POST.get("pwd")
        cpwd = request.POST.get("cpwd")
        # 2 参数校验
        if not all([user_name, pwd, cpwd]):
            return render(request, "register.html", {"errmsg": "信息请填写完整"})
        # 密码是否一致
        if pwd != cpwd:
            return render(request, "register.html", {"errmsg": "密码不一致"})
        # 3业务逻辑处理
        # 密码加密，将数据存入到数据库
        # 使用django的用户认证系统
        if len(pwd) <= 5 or len(pwd) > 10:
            return render(request,'register.html',{"errmsg":"密码长度为6-10位"})
        try:
            user = Staff.objects.create_user(user_name, None, pwd)
        except db.IntegrityError:
            # 此异常，表示用户已注册
            return render(request, "register.html", {"errmsg": "此用户已注册"})
        # 直接将用户激活
        user.is_active = True
        user.save()
        # 4 重定向到登录页面
        return redirect(reverse("app01:login"))


class LoginView(View):
    """登录"""

    def get(self, request):
        return render(request, "login.html")

    def post(self, request):
        # 1 获取到所需的数据
        user_name = request.POST.get("user_name")
        pwd = request.POST.get("pwd")
        # 2 参数校验
        if not all([user_name, pwd]):
            return render(request, "login.html", {"errmsg": "信息请填写完整"})

        # 使用django的用户认证系统直接登录
        user = authenticate(username=user_name, password=pwd)
        if user is None:
            return render(request, "login.html", {"errmsg": "用户名或密码错误"})
        # 3 查询数据库验数据
        # 在session中保存用户的登录状态信息
        login(request, user)
        # 4页面跳转到主页
        return redirect(reverse("app01:index"), {"user": user})


class LogoutView(View):
    """退出"""

    # 使用django自带的logout功能，将session删除
    def get(self, request):
        logout(request)
        return redirect(reverse("app01:index"))


class IndexView(View):
    """主页"""

    def get(self, request):
        # return render(request, "index.html")
        return redirect(reverse("app01:project"))


class ProjectView(View):
    """项目页面"""

    def get(self, request):
        # 获取所有的项目列表
        projects = Project.objects.all().order_by("create_time")
        ##分页

        per_page = 10
        paginator = Paginator(projects, per_page)
        # 处理分页

        try:
            num1 = int(request.GET.get('page', 1)) # 获取a标签传来的页码
            projects = paginator.page(num1) #得到该页码对应的数据对象列表

        except (EmptyPage, InvalidPage, PageNotAnInteger) as ex:
            projects = paginator.page(1)

        # 权限列表
        # 此用户所在的组的权限列表
        perms = request.user.get_group_permissions()
        dict = {
            "projects": projects,
            "perms": perms,
            "paginator": paginator

        }
        # if projects is not None:
        return render(request, "project.html", dict)

    def post(self, request):
        # 创建项目的页面提交
        name = request.POST.get("name")
        describe = request.POST.get("describe")
        status = request.POST.get("status")
        # 参数校验
        if not all([name, describe, status]):
            error = {
                "code": '2',
                "errmsg": "参数不完整"
            }
            return HttpResponse(json.dumps(error))
        # 项目名是否重复  # 空列表 为 False
        # 获取当前项目对象
        c_project = Project.objects.filter(name=name)
        # print c_project
        if c_project:
            error = {
                "code": '1',
                "errmsg": "项目名重复，请重新填写"
            }
            return HttpResponse(json.dumps(error))
        # 存入数据库
        Project.objects.create(name=name, describe=describe, status=status)
        # perms= request.user.get_group_permissions()

        data = {
            "code": "0",
            "data": "保存成功"
            # "perms": perms,
        }
        # 查询所有的项目对象
        # projects = Project.objects.all().order_by("create_time")
        return HttpResponse(json.dumps(data))


class ProjectViewUpdate(View):
    def post(self, request):
        name = request.POST.get("name")
        status = request.POST.get("status")
        describe = request.POST.get("describe")
        project_id = request.POST.get("project_id")
        if not all([project_id, status, describe, name]):
            error = {
                "code": "2",
                "errmsg": "参数不全"
            }
            return HttpResponse(json.dumps(error))
        Project.objects.filter(id=project_id).update(name=name, describe=describe, status=status)
        data = {
            "code": "0",
            "msg": "修改成功"
        }
        return HttpResponse(json.dumps(data))


class ProjectViewDelete(View):
    def get(self, request):
        project_id = request.GET.get("project_id")
        if not project_id:
            error = {
                "code": "3",
                "errmsg": "参数错误"
            }
            return HttpResponse(json.dumps(error))
        project = Project.objects.filter(id=project_id)
        if not project:
            error = {
                "code": "4",
                "errmsg": "数据不能重复删除"
            }
            return HttpResponse(json.dumps(error))
        elif project:
            Project.objects.filter(id=project_id).delete()
            data = {
                "code": "0",
                "msg": "数据删除成功"
            }
            return HttpResponse(json.dumps(data))


class JobView(View):
    # 所属项目的任务列表
    def get(self, request, project_id):
        # 根据项目id获取到其所有的任务
        perms = request.user.get_group_permissions()
        jobs = Job.objects.filter(project_id_id=project_id)
        project = Project.objects.get(id=project_id)

        per_page = 10  # 每页显示两条数据
        paginator = Paginator(jobs, per_page)  # 将总分页效果展示出来
        # 以下是通过点击页码按钮，展示每个页码对应的数据，默认展示第一页的数据
        try:
            num1 = int(request.GET.get('page', 1))  # 获取a标签传来的页码
            jobs = paginator.page(num1)  # 得到该页码对应的数据对象列表

        except (EmptyPage, InvalidPage, PageNotAnInteger) as ex:
            projects = paginator.page(1)

        dict = {
            "jobs": jobs,
            "project_name": project.name,
            'project_id': project_id,
            "perms": perms,
            "paginator": paginator
        }

        # 返回任务列表页
        return render(request, "job.html", dict)

    def post(self, request, project_id):
        project_name = Project.objects.get(id=project_id)
        name = request.POST.get("name")
        status = request.POST.get("status")
        # 参数校验
        dict = {
            "code": "2",
            "errmsg": "参数不完整",
            "project_id": project_id,
            "project_name": project_name
        }
        if not all([name, status]):
            return HttpResponse(json.dumps(dict))
            # 存入数据库
        Job.objects.create(project_id_id=project_id, name=name, status=status)

        dict = {
            "code": "0",
            "msg": "保存成功",
            "project_id": project_id
        }
        return HttpResponse(json.dumps(dict))


class JobViewUpdate(View):
    def post(self, request):
        # 获取创建任务的数据，并渲染到任务列表
        job_id = request.POST.get('job_id')
        name = request.POST.get("name")
        status = request.POST.get("status")

        # 参数校验
        dict = {
            "code": "2",
            "errmsg": "参数不完整"
        }
        if not all([name, status]):
            # 重新返回创建任务页面
            return HttpResponse(json.dumps(dict))
        job = Job.objects.filter(id=job_id)
        if not job:
            dict = {
                "code": "4",
                "errmsg": "数据不存在"
            }
            return HttpResponse(json.dumps(dict))
        # 修改数据库
        Job.objects.filter(id=job_id).update(name=name, status=status)
        # 错误代码

        dict = {
            "code": "0",
            "msg": "保存成功"
        }
        # 查询当前项目下所有的任务名
        # 返回任务列表页
        return HttpResponse(json.dumps(dict))


class JobViewDelete(View):
    def get(self, request):
        job_id = request.GET.get('job_id')
        # job = Job.objects.get(id=job_id)
        if not job_id:
            dict = {
                "code": "4",
                "errmsg": "任务不存在"
            }
            return HttpResponse(json.dumps(dict))
        Job.objects.get(id=job_id).delete()

        dict = {
            "code": "0",
            "msg": "删除成功"
        }
        return HttpResponse(json.dumps(dict))


class TaskView(View):
    """工作"""

    def get(self, request, job_id):
        # 获取到的数据
        # 权限列表
        perms = request.user.get_group_permissions()
        project_name = Job.objects.get(id=job_id).project_id.name
        job_name = Job.objects.get(id=job_id)
        user_name = str(request.user)
        tasks = Task.objects.filter(job_id=job_id)
        per_page = 10  # 每页显示两条数据
        paginator = Paginator(tasks, per_page)  # 将总分页效果展示出来
        # 以下是通过点击页码按钮，展示每个页码对应的数据，默认展示第一页的数据
        try:
            num1 = int(request.GET.get('page', 1))  # 获取a标签传来的页码
            tasks = paginator.page(num1)  # 得到该页码对应的数据对象列表

        except (EmptyPage, InvalidPage, PageNotAnInteger) as ex:
            tasks = paginator.page(1)
        dict = {
            "project_name": project_name,
            "job_name": job_name,
            "tasks": tasks,
            "job_id": job_id,
            "perms": perms,
            "paginator": paginator,
            "user_name": user_name,
        }
        return render(request, "task.html", dict)

    def post(self, request, job_id):
        # 提交创建工作表单
        # 查询到的数据
        project_id = Job.objects.get(id=job_id).project_id.id
        user_name = request.user
        # 表单获取的数据
        content = request.POST.get("content")
        s1 = request.POST.get("start_time")
        s2 = request.POST.get("end_time")
        dict = {
            "code": "2",
            "errmsg": "参数不完整"
        }
        if not all([content, s1, s2]):
            # 重新返回创建任务页面
            return HttpResponse(json.dumps(dict))
        d1 = datetime.datetime.strptime(s1, "%Y-%m-%d %H:%M")
        d2 = datetime.datetime.strptime(s2, "%Y-%m-%d %H:%M")
        start_time = time.mktime(d1.timetuple())
        end_time = time.mktime(d2.timetuple())
        duration = int((end_time - start_time) / 60)
        # 存入数据库
        Ta = Task.objects.create(project_id_id=project_id, job_id_id=job_id, content=content, duration=duration,
                                 start_time=s1, end_time=s2)
        # 获取创建工作的用户对象
        user = Staff.objects.get(username=user_name)
        # 谁创建的什么工作内容一并存入数据库（多对多存储数据）
        Ta.staff_id.add(user)
        dict = {
            "code": "0",
            "msg": "工作保存成功"
        }
        return HttpResponse(json.dumps(dict))


# 删除工作
class TaskDeleteView(View):
    def get(self, request):
        task_id = request.GET.get('task_id')
        print task_id
        if not task_id:
            dict = {
                "code": "4",
                "errmsg": "工作不存在"
            }
            return HttpResponse(json.dumps(dict))
        Task.objects.get(id=task_id).delete()
        dict = {
            "code": "0",
            "msg": "删除成功"
        }
        return HttpResponse(json.dumps(dict))


class TaskUpdateView(View):
    def post(self, request):
        # 表单获取的数据
        task_id = request.POST.get('task_id')
        content = request.POST.get("content")
        s1 = request.POST.get("start_time")
        s2 = request.POST.get("end_time")
        dict = {
            "code": "2",
            "errmsg": "参数不完整"
        }
        if not all([content, s1, s2]):
            # 重新返回创建任务页面
            return HttpResponse(json.dumps(dict))
        d1 = datetime.datetime.strptime(s1, "%Y-%m-%d %H:%M")
        d2 = datetime.datetime.strptime(s2, "%Y-%m-%d %H:%M")
        start_time = time.mktime(d1.timetuple())
        end_time = time.mktime(d2.timetuple())
        duration = int((end_time - start_time) / 60)
        # 修改数据库
        Task.objects.filter(id=task_id).update(content=content, duration=duration, start_time=s1, end_time=s2)
        dict = {
            "code": "0",
            "msg": "修改成功"
        }
        return HttpResponse(json.dumps(dict))
